<template>
  <basic-container>
    <div class="container-body">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-row>
          <el-form-item label="计划名称" label-width="82px">
            <el-input size="small" v-model="query.planName" placeholder="计划名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="计划内外" label-width="82px">
            <el-select v-model="query.isOutPlan" clearable>
              <el-option label="计划内" :value="false"></el-option>
              <el-option label="计划外" :value="true"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关联项目" label-width="82px">
            <el-select v-model="query.hasProject" clearable>
              <el-option label="未关联" :value="false"></el-option>
              <el-option label="已关联" :value="true"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="审计类型" label-width="82px">
            <el-select v-model="query.auditType" clearable>
              <el-option v-for="dict in dict.type.audit_type" v-if="dict.value !== '0'" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审批状态" label-width="82px">
            <el-select v-model="query.auditStatus" clearable>
              <el-option v-for="dict in dict.type.audit_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年度" label-width="82px">
            <el-select v-model="query.planHeadYear" clearable>
              <el-option v-for="planHeadYear in planHeadYears" :key="planHeadYear" :label="planHeadYear" :value="planHeadYear"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch" :loading="loading">搜索
          </el-button>
          <el-button size="small" icon="el-icon-delete" @click="searchReset" :loading="loading">清空</el-button>
        </el-form-item>
      </el-form>
      <div class="btn-operate">
        <el-button @click="showAddView" type="primary" size="small" icon="el-icon-plus">
          新增计划
        </el-button>
      </div>
      <el-table header-row-class-name="container-table-header" :data="data" size="small" style="width: 100%;margin-bottom: 20px;"
                highlight-current-row @cell-click="handleCellClick"
                row-key="id" border stripe v-loading="loading">
        <el-table-column prop="planHeadYear" label="年度" width="80">
        </el-table-column>
        <el-table-column prop="planName" label="计划名称">
        </el-table-column>
        <el-table-column prop="auditedCompanyName" label="被审计单位">
        </el-table-column>
        <el-table-column prop="auditType" label="审计类型">
          <template slot-scope="scope">
            <DictTag :options="dict.type.audit_type" :value="scope.row.auditType"></DictTag>
          </template>
        </el-table-column>
        <el-table-column prop="isOutPlan" label="计划内外">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isOutPlan > 0 | tureOrFalseTag">{{ scope.row.isOutPlan > 0 | isOutPlanTureOrFalse }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hasProject" label="关联立项">
          <template slot-scope="scope">
            <el-tag :type="scope.row.projectId > 0 | tureOrFalseTag">{{ scope.row.projectId > 0 | tureOrFalse }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审批状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.auditStatus | auditStatusTag">{{ scope.row.auditStatus | auditStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-button v-if="permissions.plan_get" type="text" size="small" icon="el-icon-view" @click="showViewBox(scope.row)">查看</el-button>
            <el-button v-if="permissions.plan_add && (scope.row.auditStatus === 0 || scope.row.auditStatus === 2)" type="text" size="small" icon="el-icon-edit" @click="showEditBox(scope.row)">编辑
            </el-button>
            <el-button v-if="scope.row.taskId" type="text" size="small" icon="el-icon-edit" @click="showTaskAuditTaskDialog(scope.row)">审批</el-button>
            <el-button v-if="scope.row.auditStatus > 0" type="text" size="small" icon="el-icon-view" @click="showTaskAuditLogDialog(scope.row)">审批日志</el-button>
            <el-button v-if="permissions.plan_del" type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="container-page">
        <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="formTitle" fullscreen custom-class="ledger" :visible.sync="formBox" :close-on-click-modal="!formBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label-width="100px" label="计划年度:" prop="planHeadYear" :rules="{required: true, message: '计划年度不能为空', trigger: ['blur', 'change']}">
              <el-select v-model="form.planHeadYear">
                <el-option v-for="planHeadYear in planHeadYears" :key="planHeadYear" :label="planHeadYear" :value="planHeadYear"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="100px" label="编制人:" prop="compiler">
              {{form.compiler}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="编制日期:" prop="planDate">
              <el-date-picker placement="bottom-start" v-model="form.planDate" type="date" placeholder="编制日期（为空时则为保存时间）"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">基本信息</div>
        <el-row>
          <el-col :span="8">
            <el-form-item label-width="100px" label="计划名称:" prop="planName" :rules="{required: true, message: '计划名称不能为空', trigger: ['blur', 'change']}">
              <el-input v-model="form.planName" placeholder="计划名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="100px" label="审计类型:" prop="auditType" :rules="{required: true, message: '审计类型不能为空', trigger: ['blur', 'change']}">
              <el-select v-model="form.auditType">
                <el-option v-for="dict in dict.type.audit_type" v-if="dict.value !== '0'" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="100px" label="审计子类型:" :rules="{required: true, message: '审计子类型不能为空', trigger: ['blur', 'change']}" v-if="form.auditType === 1">
              <el-select v-model="form.auditTypeSub" placeholder="请选择">
                <el-option v-for="dict in dict.type.audit_type_1_sub" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label-width="100px" label="被审计单位:" prop="auditedCompanyId" :rules="{required: true, message: '被审计单位不能为空', trigger: ['blur', 'change']}">
              <el-input v-model="form.auditedCompanyName" @focus="showTransferDialog(['auditedCompanyId','auditedCompanyName'], 'company', false, 2)" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label-width="100px" label="审计区间:" prop="auditDates">
              <el-date-picker placement="bottom-start" v-model="form.auditDates" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label-width="100px" label="被审计个人:" prop="auditedUserIds">
              <el-input v-model="form.auditedUserNames" @focus="showTransferDialog(['auditedUserIds','auditedUserNames'], 'auditedUser', false)" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label-width="100px" label="计划时间:" prop="planDates">
              <el-date-picker placement="bottom-start" v-model="form.planDates" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button type="primary" @click="submit" size="small" icon="el-icon-check">保存</el-button>
        <el-button type="primary" @click="submitAudit" size="small" icon="el-icon-check">保存送审</el-button>
      </span>
    </el-dialog>

    <el-dialog top="5vh" :title="formTitle" :visible.sync="viewBox"
               :append-to-body="true" :before-close="closeViewBox" width="1000px">
      <PlanAuditView :params="form"></PlanAuditView>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeViewBox" size="small" icon="el-icon-close">关闭</el-button>
      </span>
    </el-dialog>

    <TaskAuditDialog :dialog="taskAuditDialog" @setValue="setTaskAuditTaskDialog" @closeDialog="closeTaskAuditTaskDialog" ref="taskAuditDialog" />
    <TaskAuditLogDialog :dialog="taskAuditLogDialog" :process-id="processId" @closeDialog="closeTaskAuditTaskLogDialog"/>
    <FormTransfer :transferDialog="transferDialog" :transferDialogType="transferDialogType" :multiple="transferDialogMultiple" :transferCurrent="transferCurrent" @transferData="transferDataHandle" @closeTransfer="closeTransfer"/>
  </basic-container>
</template>

<script>
import {mapGetters} from "vuex";
import Tinymce from '@/components/Tinymce'
import {delObj, fetchList, getObj, submit, submitAudit, listPlanHeadYear} from "@/api/adis/work/plan";
import FormTransfer from "@/components/form/transfer";
import TaskAuditDialog from "@/components/act/TaskAuditDialog";
import TaskAuditLogDialog from "@/components/act/TaskAuditLogDialog";
import PlanAuditView from "@/components/actForm/PlanAuditView";
import {isOutPlanTureOrFalse} from "@/filters";

export default {
  directives: {
  },
  components: {
    PlanAuditView,
    Tinymce,
    FormTransfer,
    TaskAuditDialog,
    TaskAuditLogDialog,
  },
  dictTypes: ['audit_type', 'audit_type_1_sub', 'audit_status'],
  data() {
    return {
      importBox: false,
      viewBox: false,
      formBox: false,
      formTitle: '',
      loading: false,
      query: {},
      form: {
      },
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      data: [],
      selectionRow: [],
      planHeadYears: [],
      Authorization: '',
      fileList: [], // 文件

      transferDialog: false,
      transferDialogType: '',
      transferDialogArr: [],
      transferDialogMultiple: false,
      transferCurrent: {},

      taskAuditDialog: false,
      taskAuditLogDialog: false,
      processId: ''
    }
  },
  computed: {
    ...mapGetters(["permissions","userInfo"])
  },
  created() {
    this.onLoad(this.page);
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    isOutPlanTureOrFalse,
    handleCellClick(row, column) {
      if (row && column.label !== "操作"){
        this.showViewBox(row)
      }
    },

    submit() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          if(this.form.auditDates) {
            this.form.auditStartDate = this.form.auditDates[0];
            this.form.auditEndDate = this.form.auditDates[1];
          }
          if(this.form.planDates) {
            this.form.planStartDate = this.form.planDates[0];
            this.form.planEndDate = this.form.planDates[1];
          }
          if (!this.form.planDate){
            this.form.planDate= new Date().toISOString();
          }
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          this.loading = true;
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submitAudit() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          if(this.form.auditDates) {
            this.form.auditStartDate = this.form.auditDates[0];
            this.form.auditEndDate = this.form.auditDates[1];
          }
          if(this.form.planDates) {
            this.form.planStartDate = this.form.planDates[0];
            this.form.planEndDate = this.form.planDates[1];
          }
          if (!this.form.planDate){
            this.form.planDate= new Date().toISOString();
          }
          this.loading = true;
          submitAudit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    showAddView() {
      this.formTitle = '计划外添加';
      this.formBox = true;
      this.form = {
        compilerId : this.userInfo.userId,
        compiler : this.userInfo.realname,
      };
    },
    showEditBox(row) {
      getObj(row.planId).then((res) => {
        this.form = res.data.data;
        this.form.compilerId = this.userInfo.userId
        this.form.compiler = this.userInfo.realname
        if(this.form.auditStartDate && this.form.auditEndDate) {
          this.$set(this.form, "auditDates", [this.form.auditStartDate, this.form.auditEndDate]);
        }
        if(this.form.planStartDate && this.form.planEndDate) {
          this.$set(this.form, "planDates", [this.form.planStartDate, this.form.planEndDate]);
        }
        if(res.data.data.fileUrl) {
          this.fileList.push({url:res.data.data.fileUrl});
        }
        this.formTitle = row.planName;
        this.formBox = true;
      });
    },
    showViewBox(row) {
      getObj(row.planId).then((res) => {
        this.form = res.data.data;
        this.formTitle = row.planName;
        this.viewBox = true;
      });
    },
    closeViewBox() {
      this.viewBox = false;
    },
    handleDelete(row) {
      this.$confirm("确定将选择的数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delObj(row.renterId);
      })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    resetForm() {
      this.formBox = false;
      this.viewBox = false;
      this.form = {};
      this.formTitle = '';
      this.$refs['optForm'] && this.$refs['optForm'].resetFields();
      this.viewBox = false;
      this.printBox = false;
      this.onLoad(this.page);
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if(this.query.publishDates) {
        this.query.startDate = this.query.publishDates[0];
        this.query.endDate = this.query.publishDates[1];
      }
      fetchList(Object.assign(params, this.query, page)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.listPlanHeadYear()
      }, () => {
        this.loading = false;
      });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    handlePreview(file) {
      window.open(file.url ? file.url : file.response.data.url)
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    showTransferDialog(transferDialogArr, transferDialogType, transferDialogMultiple, transferDialogQuery) {
      this.transferDialogArr = transferDialogArr; // 表单字段
      this.transferDialogType = transferDialogType; // 判断类型user:人员，unit:职位，department:部门,company:单位,plan:计划等
      this.transferDialogMultiple = transferDialogMultiple; // 是否多选
      if (transferDialogType === 'company') {
        this.transferCurrent.type = transferDialogQuery;
      }
      if (transferDialogType === 'user') {
        if(!transferDialogQuery) {
          this.$message({
            type: "warning",
            message: "请先选择单位!"
          });
          return
        }
        this.transferCurrent.deptId = transferDialogQuery;
      }
      //重组数组name和id
      this.transferCurrent.currentval = []
      if(this.form[transferDialogArr[0]]) {
        if (this.form[transferDialogArr[0]].indexOf(',') > -1) {
          this.form[transferDialogArr[0]].split(',').forEach((item, i) => {
            this.transferCurrent.currentval.push({name: this.form[transferDialogArr[1]].split(',')[i], id: item})
          })
        } else {
          this.transferCurrent.currentval = [{name: this.form[transferDialogArr[1]], id: this.form[transferDialogArr[0]]}]
        }
      }
      this.transferDialog = true;
    },
    transferDataHandle(e) {
      this.transferDialog = false
      this.currentval = e.list
      let currentId = [], currentName = []
      if (e.list.length > 1) {
        e.list.forEach(item => {
          currentId.push(item.id)
          currentName.push(item.name)
        })
      } else {
        currentId = [e.list[0].id]
        currentName = [e.list[0].name]
      }
      this.$set(this.form, this.transferDialogArr[0], currentId.join(','))
      this.$set(this.form, this.transferDialogArr[1], currentName.join(','))
    },
    closeTransfer() {
      this.transferDialog = false;
    },

    // 获取所有已经审批通过的年度计划年度
    listPlanHeadYear(){
      listPlanHeadYear().then((res) => {
        this.$set(this,"planHeadYears", res.data.data)
      });
    },
    /**=========审批相关==begin===========*/
    showTaskAuditTaskDialog(row) {
      this.taskAuditDialog = true;
      this.$refs['taskAuditDialog'].initData({taskId: row.taskId, processId: row.processId});
    },
    closeTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
    },
    setTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
      this.onLoad(this.page);
    },
    showTaskAuditLogDialog(row) {
      this.processId = row.processId;
      this.taskAuditLogDialog = true;
    },
    closeTaskAuditTaskLogDialog() {
      this.taskAuditLogDialog = false;
    },
    /**=========审批相关==end===========*/
  }
};
</script>

<style>
</style>
